import BaseModal, { ModalFC } from '@/components/base/BaseModal';
import BaseTableTransfer from '@/components/base/BaseTransfer/BaseTableTransfer';
import { useRequest } from '@/utils/request';
import { Col, Row, Spin } from 'antd';
import { useState } from 'react';
import styled from 'styled-components';
import { getRoleInfoAllList, getRolesBindPermissions } from '../../RoleInfo/api';
import PermissionTree from '../../RoleInfo/components/PermissionTree';
import { getUserRoles, saveUserRoles } from '../api';

const FlexCol = styled(Col)`
  && {
    display: flex;
  }
  .flex1 {
    flex: 1;
  }
`;
const flatten = (list: Record<string, any>[] = []) => {
  const resArr: Record<string, any>[] = [];
  list.forEach((item: any) => {
    const resItem = { ...item };
    const children = resItem.operationsList
      ? resItem.operationsList.map((i: any) => {
          return { id: i.id, label: i.name };
        })
      : resItem.permissionTreeVOList;

    resItem.children = flatten(children);
    resArr.push(resItem);
  });
  return resArr;
};
const BindRoleModal: ModalFC<{ userId: string }> = ({ userId, onCancel, ...anyProps }) => {
  const [roleIds, setRoleIds] = useState<string[]>([]);
  const roleData = useRequest(getRoleInfoAllList, {});

  const roleBindPermissions = useRequest(getRolesBindPermissions, {
    manual: true
  });
  console.log(roleBindPermissions);
  const getRoleBind = (ids: string[]) => {
    if (ids.length > 0) {
      roleBindPermissions.run(ids);
    } else {
      roleBindPermissions.mutate([]);
    }
  };
  useRequest(getUserRoles, {
    defaultParams: [userId],
    onSuccess(data) {
      const ids = data.map((i) => i.id);
      getRoleBind(ids);
      setRoleIds(ids);
    }
  });
  const save = useRequest(saveUserRoles, {
    manual: true,
    onSuccess() {
      onCancel();
    }
  });
  return (
    <BaseModal
      title='用户角色分配'
      width={1000}
      {...anyProps}
      onOk={() => {
        save.run(userId, roleIds);
      }}
      okButtonProps={{ disabled: roleData.loading, loading: save.loading }}
      onCancel={onCancel}
    >
      <Row gutter={8}>
        <Col span={14}>
          <h4>角色分配</h4>
          <Spin spinning={roleData.loading}>
            <BaseTableTransfer
              titles={['未绑定角色', '已绑定角色']}
              dataSource={roleData.data || []}
              targetKeys={roleIds}
              onChange={(t) => {
                setRoleIds(t);
                getRoleBind(t);
              }}
              bodyHeight={300}
              rowKey={(record) => record.id}
              leftColumns={[
                { dataIndex: 'roleName', title: '角色名称' },
                { dataIndex: 'remarks', title: '备注' }
              ]}
              rightColumns={[
                { dataIndex: 'roleName', title: '角色名称' },
                { dataIndex: 'remarks', title: '备注' }
              ]}
            />
          </Spin>
        </Col>
        <FlexCol span={10}>
          <Spin wrapperClassName='flex1' spinning={roleBindPermissions.loading}>
            <h4>拥有权限</h4>
            <PermissionTree treeData={flatten(roleBindPermissions.data || [])} checkable={false} />
          </Spin>
        </FlexCol>
      </Row>
    </BaseModal>
  );
};

export default BindRoleModal;
